package com.android.likeweixin.asynctask;

import java.util.Map;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;

/**
 * 异步任务基础类，目的是减少使用手动创建的Thread(开销较大，频繁创建很不友好)，
 * 减少使用Handler(使用不当造成很容易引人内存泄露)，慎用mHandler.post(因其在UI线程中做事，一不小心阻塞UI)。
 * 
 * 1.支持Activity,Service中异步任务的相关回调，代码接口统一，进度框统一处理，返回数据统一处理，异步逻辑代码分离。
 * 2.支持API11及以后的SDK的线程池并行处理任务，解决默认方式下的性能瓶颈。
 * 3.可以把基于网络请求和返回的数据解析、大批量查询本地数据库或读写文件放在Task子类中操作
 * ，把UI更新操作回调Activity来做，Service同样道理。
 * 
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public abstract class BaseAsyncTask extends
		AsyncTask<Object, Integer, Map<String, Object>> {
	protected Context mContext;

	protected AsyncTaskCallback mCallback;

	protected Handler mHandler;

	/** 请求标识,据此执行业务代码 */
	protected int type;

	public BaseAsyncTask(Context context, int type, Handler handler) {
		this.mContext = context;
		if (this.mContext instanceof AsyncTaskCallback) {
			this.mCallback = (AsyncTaskCallback) this.mContext;
		}
		this.type = type;
		this.mHandler = handler;
	}

	public BaseAsyncTask(Context context, int type) {
		this.mContext = context;
		if (this.mContext instanceof AsyncTaskCallback) {
			this.mCallback = (AsyncTaskCallback) this.mContext;
		}
		this.type = type;
	}

	public static final int PROGRESS_START = 0;

	public static final int PROGRESS_END = -1;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		if (this.mCallback != null) {
			this.mCallback.onProgressUpdate(type, 0);
		}
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		if (this.mCallback != null) {
			this.mCallback.onCancel(type);
		}
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		if (this.mCallback != null) {
			this.mCallback.onProgressUpdate(type, values[0]);
		}
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressWarnings("unchecked")
	public void execut(Object... params) {
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB) {
			super.execute(params);
		} else {
			super.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
		}
	}

	@Override
	protected abstract Map<String, Object> doInBackground(Object... params);

	@Override
	protected void onPostExecute(Map<String, Object> result) {
		super.onPostExecute(result);
		if (this.mCallback != null) {
			this.mCallback.onPostExecute(type, result);
		}
	}
}
